package com.unlcn.erp.hyc.interfaces.backend.service;

import com.alibaba.fastjson.JSONObject;
import com.unlcn.erp.hyc.interfaces.backend.bo.HYCOrderDB;
import com.unlcn.erp.hyc.interfaces.backend.bo.OrderCodesDB;
import com.unlcn.erp.hyc.interfaces.backend.enums.CallHYCUrlTypeEnum;
import com.unlcn.erp.hyc.interfaces.base.mapper.HycExceptionMsgMapper;
import com.unlcn.erp.hyc.interfaces.base.mapper.HycbackMapper;
import com.unlcn.erp.hyc.interfaces.base.mapper.HycorderMapper;
import com.unlcn.erp.hyc.interfaces.base.mapper.SoorderMapper;
import com.unlcn.erp.hyc.interfaces.base.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 获取订单信息
 * Created by zhiche024 on 2017/9/2.
 */
@Service
public class CallOrderByHYCServiceImpl implements CallOrderByHYCService{

    private static final Logger LOGGER = LoggerFactory.getLogger(CallOrderByHYCServiceImpl.class);

    private static final String ORDER = "ORDER" ,ORDERDETAILS = "ORDERDETAILS";

    @Autowired
    private CallHYCUrlReceiveService callHYCUrlReceiveService;

    @Autowired
    private CheckIntermediateService checkIntermediateService;
    @Autowired
    private HycorderMapper hycorderMapper;
    @Autowired
    private SoorderMapper soorderMapper;
    @Autowired
    private HycbackMapper hycbackMapper;
    @Autowired
    private HycExceptionMsgMapper hycExceptionMsgMapper;
    @Autowired
    private ExecptionDisposeService execptionDisposeService;


    /**
     * 获取定单号列表
     */
    @Override
    public void getOrderCodes() throws Exception{

        //调用接口获取订单号列表；
        String data = callHYCUrlReceiveService.callHYCUrlReceive(ORDER, null);
        //将接口返回的数据进行拆分；
        List<OrderCodesDB> OrderCodes= JSONObject.parseArray(data,OrderCodesDB.class);

        for(int i = 0; i < OrderCodes.size() ; i++ ){
            OrderCodesDB orderCodedb = OrderCodes.get(i);
            try{
                this.getOrderDetails(orderCodedb.getCode());
            }catch (Exception e){
                execptionDisposeService.saveExecption(e.toString(),orderCodedb.getCode(),CallHYCUrlTypeEnum.HYC_ORDERDETAILS.getValue());
                LOGGER.error("订单保存出错:"+ orderCodedb.getCode());
            }
        }
    }


    /**
     * 获取定单详细信息
     * @param db
     * @throws Exception
     */
    private void updateHYCDetails(HYCOrderDB db) throws Exception{
        //根据订单号获取订单详细信息
        Hycorder order = new Hycorder();
        BeanUtils.copyProperties(db,order);
        //更新HYC订单为新数据
        hycorderMapper.updateByOrderCode(order);
    }

    /**
     * 存入
     * @param orderCode
     * @throws Exception
     */
    @Override
    public void saveOrderByCode(String orderCode) throws Exception{
        try{
            this.getOrderDetails(orderCode);
        }catch (Exception e){
            execptionDisposeService.saveExecption(e.toString(),orderCode,CallHYCUrlTypeEnum.HYC_ORDERDETAILS.getValue());
            LOGGER.error("订单保存出错:"+orderCode);
        }
    }


    /**
     *获取定单详细信息
     * @param orderCode 订单号
     */
    @Override
    public void getOrderDetails(String orderCode) throws Exception{
        //根据订单号获取订单详细信息
        String data = callHYCUrlReceiveService.callHYCUrlReceive(ORDERDETAILS,orderCode);
        if(data == null){
            LOGGER.error(orderCode+"该订单查询的数据为空");
        }
        HYCOrderDB db = JSONObject.parseObject(data, HYCOrderDB.class);

        //将获取的数据保存到订单中间表中 需要判断是否存在，如果存在则更新，不过不存在则新增
        //检查该订单号是否已经录入
        HycorderExample example = new HycorderExample();
        example.createCriteria().andOrdercodeEqualTo(orderCode);
        int count = hycorderMapper.countByExample(example);

        if(count >0){
            this.updateHYCDetails(db);
        }
        else{
            this.saveHYCOrder(db);
        }

        //检查城市，分供方，车型，客户是否存在
        //判断城市是否存在
        Smcitymap startCity = checkIntermediateService.judgeCityMap(db.getDepartcitycode(),db.getDepartcityname(),orderCode);//起运城市
        Smcitymap endCity = checkIntermediateService.judgeCityMap(db.getReceiptcitycode(),db.getReceiptcityname(),orderCode);//目的城市

        if(startCity == null ||endCity == null){
            LOGGER.error("城市保存失败");
            return;
        }

        //判断该客户体系是否已存在
        Long custId = checkIntermediateService.judgeCust(db.getCustomername());
        //判断客户是否存在
        Long customerId = checkIntermediateService.judgeCustomerpMap(db.getCustomerid(),db.getCustomername(),startCity.getVccityid(),custId);
        db.setCustomerid(customerId);
        //判断客户合同是否存在
        Long contractId = checkIntermediateService.judgeSmContract(customerId);
        db.setIcontractid(contractId);
        //判断子合同（装车点）是否存在
        Long warehouseId = checkIntermediateService.judgeSmWarehouse(customerId,contractId,startCity);
        db.setIwarehouseid(warehouseId);
        //判断车型是否存在
        Long modersId = checkIntermediateService.judgeModersMap(db.getVehicleid(),db.getVehiclename(),contractId);
        db.setVehicleid(modersId);
        //将订单详细信息写入到soorder中
        saveHYCOrderToSMOder(db,startCity,endCity);

        LOGGER.info(orderCode+"该订单的保存成功！");
    }
    /**
     * 保存数据到erp中的HYC订单中间表中
     * @param db 订单数据
     */
    public void saveHYCOrder(HYCOrderDB db){
        Hycorder order = new Hycorder();
        BeanUtils.copyProperties(db,order);
        hycorderMapper.insertHYCOrder(order);
    }

    /**
     * 将订单中间表存入到soorder中
     * @param db
     */
    public void saveHYCOrderToSMOder(HYCOrderDB db,Smcitymap startCity,Smcitymap endCity) throws Exception{

        SoorderExample example = new SoorderExample();
        example.createCriteria().andVcordernoEqualTo(db.getOrdercode());
        List<Soorder> orders= soorderMapper.selectByExample(example);

        if(CollectionUtils.isEmpty(orders)){
            //将订单中间表存入到soorder中
            //判断提车库是否存在
            Long getPointId = checkIntermediateService.judgeGetPointIsExist(db.getCustomerid(),startCity.getVccityname(), db.getDepartprovincename());
            Long ilineid = soorderMapper.getNextIlineid();
            Soorder soorder = new Soorder();
            soorder.setIlineid(ilineid);
            soorder.setVcorderno(db.getOrdercode());
            soorder.setVccustorderno(db.getCustomerordercode());
            soorder.setIcustomerid(db.getCustomerid());
            soorder.setIcontractid(db.getIcontractid());
            soorder.setIwarehouseid(db.getIwarehouseid());
            if("".equals(db.getUsername()) || db.getUsername() == null ){
                soorder.setVcuserno("system");
            }else {
                soorder.setVcuserno(db.getUsername());
                soorder.setVcreceiveduty(db.getUsername());
            }
            soorder.setDtdate(db.getCreatetime());
            soorder.setVcaddress(db.getDepartaddr());
            soorder.setVccontact(db.getDepartcontact());
            soorder.setVctel(db.getDepartphone());
            soorder.setVcaddress2(db.getReceiptaddr());
            soorder.setVccontact2(db.getReceiptcontact());
            soorder.setVctel2(db.getReceiptphone());
            soorder.setVcstartcity(startCity.getVccityname());
            soorder.setVccityname(endCity.getVccityname());
            soorder.setBurgent((short)0);
            soorder.setIstyleid(db.getVehicleid());//插入erp货物型号
            soorder.setVcstyleno(db.getVehiclename());
            soorder.setVcunit("辆");
            soorder.setDcqty((short)1);
            soorder.setDcshipedqty((short)0);
            soorder.setVcmemo(db.getComment());
            if(db.getIscash() != null){
                if(db.getIscash() == 0){
                    soorder.setIpayid(1);
                }else{
                    soorder.setIpayid(2);
                }
            }else{
                LOGGER.error("该订单好现金标记为NULL："+db.getOrdercode());
            }
            soorder.setDcpay(db.getCost());
            if(db.getPaystatus() == 30){ //10, "未支付",20, "待支付",30, "已支付"
                soorder.setDcpayed(db.getCost());
                soorder.setDccash2(db.getCost());
            }else{
                soorder.setDcpayed(BigDecimal.valueOf(0));
                soorder.setDccash2(BigDecimal.valueOf(0));
            }
            soorder.setDckilometer(db.getDistance());
            soorder.setDcqty2((short)0);
            soorder.setIpid((long)0);
            soorder.setIorderid(ilineid);
            soorder.setDcjsqty((short)0);
            soorder.setDcprice((short)0);
            soorder.setIdeptid((short)0);
            soorder.setDccustqty((short)0);
            soorder.setIkilometerflag((short)0);
            soorder.setIpriceflag((short)0);
            soorder.setIshipid((short)0);
            soorder.setDtcreatedate(new Date());
            soorder.setDccash1(BigDecimal.valueOf(0));
            soorder.setIpayid2((short)1);
            soorder.setDcalkilometer((short)0);
            soorder.setDcalprice((short)0);
            soorder.setIcheckid((short)1);
            soorder.setVccheckmemo("来源于慧运车导入");
            soorder.setVccheckuserno("system");
            soorder.setIpassid((short)0);
            soorder.setBactive((short)0);
            soorder.setIflag((short)0);
            soorder.setIfleetid((short)0);
            soorder.setImodeid((short)2);
            soorder.setVcvin(db.getVin());
            soorder.setIgetpoint(getPointId);
            soorder.setIdestid(0);
            soorder.setIdealerid((short)0);
            soorder.setIcustmodeid((short)0);
            soorder.setBneedReceipt((short)1);
            soorder.setIendpoint((short)0);
            soorder.setIarcityid((short)0);
            soorder.setIsdispatch((short)0);
            soorder.setDataresource("来源于慧运车导入");
            soorderMapper.saveSoorderByHYC(soorder);
        }
        else{
            Soorder soorder = orders.get(0);
            //现金还是收款
            if(db.getIscash() != null){
                if(db.getIscash() == 0){
                    soorder.setIpayid(1);
                }else{
                    soorder.setIpayid(2);
                }
            }else{
                LOGGER.error("该订单好现金标记为NULL："+db.getOrdercode());
            }
            soorder.setDcpay(db.getCost());


            /** 如果在慧运车中做收款，则打开
            if(db.getPaystatus() == 30){ //10, "未支付",20, "待支付",30, "已支付"
                soorder.setDcpayed(db.getCost());
                soorder.setDccash2(db.getCost());
            }else{
                soorder.setDcpayed(BigDecimal.valueOf(0));
                soorder.setDccash2(BigDecimal.valueOf(0));
            }
            **/
            soorderMapper.updateSaveSoorderByHYC(soorder);
        }
    }

    @Override
    public String getCustomerOrderCode(String orderCode) throws Exception {
        String customerOrderCode = "";
        //根据订单号获取订单详细信息
        String data = callHYCUrlReceiveService.callHYCUrlReceive(ORDERDETAILS,orderCode);
        if(data == null){
            LOGGER.error(orderCode+"该订单查询的数据为空");
        }
        HYCOrderDB db = JSONObject.parseObject(data, HYCOrderDB.class);
        if(!Objects.isNull(db)){
            customerOrderCode = db.getCustomerordercode();
        }
        return customerOrderCode;
    }
}
